<?php

function getPageNameFromParameters() {
    $page = "";
    $choice = $_GET['choice'];
    if ($choice == "export_termekek") {
        $page = "exportproducts";
    } else if ($choice == "import_termekek") {
        $page = "importproducts";
    } else if ($choice == "forgottenpassword") {
        $page = "forgottenpassword";
    } else if ($choice == "virtual_exhibition") {
        $page = "virtual_exhibition";
    } else if ($choice == "businessleads") {
        $page = "businessleads";
    } else if ($choice == "szolgaltatasok") {
        $page = "services";
    } else if ($choice == "gop") {
        $page = "gop";
    } else if ($choice == "virtualis_kiallitas") {
        $page = "exhibition";
    } else if ($choice == "kulfoldimagyarcegek") {
        $page = "habroad";
    } else if ($choice == "login") {
        $page = "login";
    } else if ($choice == "register") {
        $page = "register";
    } else if ($choice == "subscribe") {
        $page = "subscribe";
    } else if ($choice == "intro") {
        $page = "popup_intro";
    } else if ($choice == "profile") {
        $page = "companyprofile";
    } else if ($choice == "recommendations") {
        $page = "recommendations";
    } else if ($choice == "svprofile") {
        $page = "svprofile";
    } else if ($choice == "logoupload") {
        $page = "popup_logoupload";
    } else if ($choice == "popup_productsearch") {
        $page = "popup_productsearch";
    } else if ($choice == "popup_businessleads") {
        $page = "popup_businessleads";
    } else if ($choice == "list_exportproducts") {
        $page = "list_exportproducts";
    } else if ($choice == "list_services") {
        $page = "list_services";
    } else if ($choice == "list_importproducts") {
        $page = "list_importproducts";
    } else if ($choice == "list_businessleads") {
        $page = "list_businessleads";
    } else if ($choice == "list_hacompanies") {
        $page = "list_ha_company";
    } else if ($choice == "blprofile") {
        $page = "blprofile";
    } else if ($choice == "aboutus") {
        $page = "aboutus";
    } else if ($choice == "mediaoffer") {
        $page = "mediaoffer";
    } else if ($choice == "termsofuse") {
        $page = "termsofuse";
    } else if ($choice == "chambers") {
        $page = "chambers";
    } else if ($choice == "businessinhungary") {
        $page = "businessinhungary";
    } else if ($choice == "associations") {
        $page = "associations";
    } else if ($choice == "exportimportstat") {
        $page = "exportimportstat";
    } else if ($choice == "contactus") {
        $page = "contactus";
    } else if ($choice == "usefullinks") {
        $page = "usefullinks";
    } else if ($choice == "visithungary") {
        $page = "visithungary";
    } else if ($choice == "saverequest") {
        $page = "saverequest";
    } else if ($choice == "confirm") {
        $page = "confirm";
    } else if ($choice == "newsletter") {
        $page = "newsletter";
    } else if ($choice == "company_email") {
        $page = "company_email";
    } else if ($choice == "maintenance") {
        $page = "maintenance";
    } else if ($choice == "changebanners") {
        $page = "changebanners";
    } else if ($choice == "static_content") {
        $page = "static_content";
    } else if ($choice == "imagechange") {
        $page = "imagechange";
    } else if ($choice == "chambers") {
        $page = "chambers";
    } else if ($choice == "discount") {
        $page = "discount";
    } else if ($choice == "emails") {
        $page = "emails";
    } else if ($choice == "group_members") {
        $page = "group_members";
    } else if ($choice == "svcrecommend") {
        $page = "svcrecommend";
    } else if ($choice == "bulkemails") {
        $page = "bulkemails";
    } else if ($choice == "invoices") {
        $page = "invoices";
    } else if ($choice == "personalprofile") {
        $page = "personalprofile";
    } else if ($choice == "scheduled_emails") {
        $page = "scheduled_emails";
    }
    return $page;
}

function getDatedifference($from, $to) {
    $fromymd = explode("-", $from);
    $toymd = explode("-", $to);
    $fromts = strtotime($fromymd[2]."-".$fromymd[1]."-".$fromymd[0]);
    $tots = strtotime($toymd[2]."-".$toymd[1]."-".$toymd[0]);
    $diff = abs($fromts-$tots);
    $diffdays = $diff / 24 / 60 / 60;
    return ceil($diffdays);
}

function removeAccents($str) {
    $subst = array(
        "é" => "e",
        "á" => "a",
        "ű" => "u",
        "ő" => "o",
        "ú" => "u",
        "ö" => "o",
        "ü" => "u",
        "ó" => "o",
        "í" => "i",
        "É" => "E",
        "Á" => "A",
        "Ű" => "U",
        "Ő" => "O",
        "Ú" => "U",
        "Ö" => "O",
        "Ü" => "U",
        "Ó" => "O",
        "Í" => "I",
    );
    return str_replace(array_keys($subst), array_values($subst), $str);
}

function generateCodeFor($percent) {
    $result = "";
    $base = md5(date("Y-m-d"));
    if ($percent == 100) {
        $result = $base;
    } else if ($percent == 50) {
        $result = $base{0}.$base{2}.$base{4}.$base{6}.$base{8}.$base{10};
    } else if ($percent == 40) {
        $result = $base{1}.$base{3}.$base{5}.$base{7}.$base{9}.$base{11};
    } else if ($percent == 30) {
        $result = $base{2}.$base{4}.$base{6}.$base{8}.$base{10}.$base{12};
    } else if ($percent == 20) {
        $result = $base{3}.$base{5}.$base{7}.$base{9}.$base{11}.$base{13};
    } else if ($percent == 10) {
        $result = $base{4}.$base{6}.$base{8}.$base{10}.$base{12}.$base{14};
    }
    return $result;
}

function URL($paramArray) {
    $queryString = "";
    foreach ($paramArray as $key=>$value) {
        $queryString .= "$key=$value&";
    }
    $queryString = rtrim($queryString, "&");
    return "index.php?$queryString";
}

function getServiceTypeId($serviceTypeName) {
    $arr = array(
        "Accounting",
        "Advertising and PR agencies",
        "Air tickets, Airlines",
        "Art galleries",
        "Attorneys",
        "Auditing",
        "Banks",
        "Beauty salons, Skincare, Hair, Cosmetics",
        "Books",
        "Car importers, Fleet management",
        "Car rentals",
        "Casinos",
        "Children's entertainment",
        "Cleaning and security",
        "Computers, software",
        "Conference centers",
        "Courier and messenger services",
        "Culture",
        "Customs agents",
        "Debt management",
        "Event organizors and catering",
        "Fitness clubs",
        "Florists, gardening",
        "Furniture, home decoration",
        "Golf centers",
        "Healthcare and pharmacies",
        "Hostess service",
        "Hotels",
        "Insurance companies",
        "Logistic services",
        "Market research",
        "Office supply",
        "Printing",
        "Real estate",
        "Recruiting and HR services",
        "Relocation",
        "Restaurants",
        "Schools and universities",
        "Shipping",
        "Shopping",
        "Tax consultants",
        "Taxi",
        "Telecommunication",
        "Translators",
        "Travel agencies",
    );
    return array_search($serviceTypeName, $arr) + 1;
}

function exposeObject($name, $value) {
    $_SESSION['exposed'][$name] = serialize($value);
}

function validationSuccess() {
    return array(
        type => "validation",
        overall => true
    );
}

function validationFailed($fieldMessages) {
    return array(
        type => "validation",
        overall => false,
        msgArray => $fieldMessages
    );
}

function getExposedObject($name) {
    return unserialize($_SESSION['ewposed'][$name]);
}

function getMimeType($fileName) {
    $image = array(
        "jpg",
        "png",
        "gif",
        "bmp",
    );
    $components = explode(".", $fileName);
    $ext = $components[count($components)-1];
    if (in_array($ext, $image)) { return "image/$ext"; }
    return "text/plain";
}

function convertCheckboxValueToBoolean($val) {
    if ($val == "on" || $val == "yes") { return 1; }
    return 0;
}

function isChecked($params, $cbName, $ndx = "") {
    if ($ndx != "") {
        if ($params[$cbName][$ndx] == "on" || $params[$cbName][$ndx] == "yes") { return true; }
    } else {
        if ($params[$cbName] == "on" || $params[$cbName] == "yes") { return true; }
    }
    return false;
}

function isCheckedByValue($val) {
    if ($val == "on" || $val == "yes") { return true; }
    return false;
}

function addMonths($monthCount) {
    $now = getdate();
    $result = "";
    $now['mon'] += $monthCount;
    if ($now['mon'] > 12) {
        $now['year'] += 1;
        $now['mon'] -= 12;
    }
    if ($now['mday'] > cal_days_in_month(CAL_GREGORIAN, $now['mon'], $now['year'])) {
        $now['mday'] = cal_days_in_month(CAL_GREGORIAN, $now['mon'], $now['year']);
    }
    return $now['year'] . "-" . $now['mon'] . "-" . $now['mday'];
}

function dateIsPast($date, $datefrom = "") {
    if ($date == "") { return true; }
    if ($date == "9999-12-31") { return false; }
    $today = "";
    if ($datefrom == "") {
        $today = date("Y-m-d");
    } else {
        $today = $datefrom;
    }
    if (strtotime($today) > strtotime($date)) {
        return true;
    }
    return false;
}

function calculateMonthInterval($month) {
    $now = getdate();
    $newmonth = $now['mon'] + $month;
    if ($newmonth > 12) {
        $now['year'] += 1;
        $newmonth -= 12;
    }
    return $now['year'] ."." . $newmonth . "." . $now['mday'];
}

function convertYNValueToBoolean($val) {
    if ($val == "yes") { return 1; }
    return 0;
}

function getCaptchaObject() {
    $captchas = new CaptchasDotNet("demo", "secret", "captchas_strings", 3600, "abcdefghijklmnopqrstuvwxyz", 6, 200, 80, "646464");
    return $captchas;
}

function executeTask($taskName, $params = array()) {
    require_once("site/tasks/$taskName.php");
    call_user_func("task_$taskName", $params);
}

function getRequestParameter($paramName, $default = false) {
    if (isset($_POST[$paramName])) {
        return mysql_escape_string($_POST[$paramName]);
    } else if (isset($_GET[$paramName])) {
        return mysql_escape_string($_GET[$paramName]);
    } else if (isset($_SESSION['storedparams'][$paramName])) {
        return $_SESSION['storedparams'][$paramName];
    }
    return $default;
}

function storeParameter($paramName, $value) {
    if (!is_array($_SESSION['storedparams'])) { $_SESSION['storedparams'] = array(); }
    $_SESSION['storedparams'][$paramName] = $value;
}

function getStoredParameter($paramName, $default = false) {
    if (isset($_SESSION['storedparams'][$paramName])) { return $_SESSION['storedparams'][$paramName]; }
    return $default;
}

function addPopupResult($paramName, $paramValue) {
    global $popupResult;
    $popupResult[$paramName] = $paramValue;
}

function generatePopupResult() {
    global $popupResult;
    global $popupSubmitScripts;

    $script = array();
    $script[] = "<script>";
    $script[] = "window.parent.setPopupResult(" . json_encode($popupResult) . ");";
    $script = array_merge($script, $popupSubmitScripts);
    $script[] = "</script>";
    return implode("\r\n", $script);
}

function setPopupCloseCallback($cbName, $params = array()) {
    global $popupSubmitScripts;
    $paramString = json_encode($params);
    $popupSubmitScripts[] = "window.parent.$cbName($paramString);";
}

function addhtmlService($serviceName) {
    global $htmlServices;
    $htmlServices[] = $serviceName;
}

function sendEmail($emailName, $to, $params, $attachments = array()) {
    if ($to == "") { Log::info("addressee is empty, exiting"); return; }
    $sender = getConfigParameter("site", "noreply_email");
    $senderName = getConfigParameter("site", "noreply_name");
    $mail = new PHPMailer();
    $subst = array(
        "\\\"" => "\"",
        "/http" => "http",
    );
    foreach ($params as $key=>$value) {
        $subst["[$key]"] = $value;
    }
    Database::loadModel("email");
    $result = Database::getItem($emailName);
    $mail->Subject = $result['subject'];
    $mail->CharSet = "UTF-8";
    $mail->From = $sender;
    $mail->FromName = $senderName;
    $mail->addAddress($to);
    $mail->isHTML(true);
    for ($i = 0; $i < count($attachments); $i++) {
        $mail->addAttachment($attachments[$i]);
    }
    Log::debug("mail body=" . str_replace(array_keys($subst), array_values($subst), $result['content']));
    $mail->Body = str_replace(array_keys($subst), array_values($subst), $result['content']);
    if (!$mail->send()) {
        echo $mail->ErrorInfo;
        return $mail->ErrorInfo;
    }
}

function getEmailText($emailName, $params) {
    $subst = array();
    foreach ($params as $key=>$value) {
        $subst["[$key]"] = $value;
    }
    Database::loadModel("email");
    $result = Database::getItem($emailName);
    Log::debug("mail body=" . $result['content']);
    $result['content'] = str_replace(array_keys($subst), array_values($subst), $result['content']);
    return $result;
}

function sendEmailWithContent($to, $subject, $content, $attachments = array(), $params = array()) {
    if ($to == "") {
        Log::info("addressee is empty, skipping");
        return;
    }
    Log::info("sending email to $to (subject=$subject)");
    $sender = getConfigParameter("site", "noreply_email");
    $senderName = getConfigParameter("site", "noreply_name");
    $mail = new PHPMailer();
    $subst = array(
        "\\\"" => "\"",
    );
    foreach ($params as $key=>$value) {
        $subst["[$key]"] = $value;
    }
    $mail->Subject = $subject;
    $mail->CharSet = "UTF-8";
    $mail->From = $sender;
    $mail->FromName = $senderName;
    $mail->addAddress($to);
    for ($i = 0; $i < count($attachments); $i++) {
        $mail->addAttachment($attachments[$i]);
    }
    $mail->isHTML(true);
    $mailHtml = str_replace(array_keys($subst), array_values($subst), $content);
    $mail->Body = $mailHtml;
    Log::debug("mail HTML=$mailHtml");
    if (!$mail->send()) {
        return "Mail cannot be sent to $to: ".$mail->ErrorInfo;
    }
    Log::info("mail sent");
    return "";
}

function serviceSuccessful($result) {
    $res = array(
        data => $result,
        success => 1,
    );
    return $res;
}

function serviceSuccessfulWithRedirect($result, $page, $subpage = "", $params = array()) {
    $res = array(
        data => $result,
        redirect => array(
            page => $page,
            subpage => $subpage,
            params => $params,
        ),
        success => 1,
    );
    return $res;
}

function serviceFailure($result, $msg = "Internal error occured") {
    $res = array(
        data => $result,
        success => 0,
        msg => $msg
    );
    return $res;
}

function asImage($type, $content) {
    header("Content-type:" . $type);
    return $content;
}

function addDataService($serviceName) {
    global $dataServices;
    $dataServices[] = $serviceName;
}

function getConfigParameter($major, $minor) {
    global $_CONFIG;
    return $_CONFIG[$major][$minor];
}

function initDatabase() {
    global $_CONFIG;
    Database::setConnection($_CONFIG['db']['host'], $_CONFIG['db']['username'], $_CONFIG['db']['password'], $_CONFIG['db']['dbname'], "mysql");
}

function sophisticateData($rawData) {
// TODO: megcsinalni rendesen, hogy mukodjon tombokre is.
    return $rawData;
    $result = "";
    if (is_array($rawData)) {
        $result = array();
        foreach ($rawData as $key=>$value) {
            if (is_array($value)) {
                for ($i = 0; $i < count($value); $i++) {
                    $result[$key][$i] = mysql_real_escape_string($value[$i]);
                }
            } else {
                $result[$key] = mysql_real_escape_string($value);
            }
        }
    } else {
        $result = mysql_real_escape_string($rawData);
    }
    return $result;
}

function buildServiceURL($pageName, $serviceName, $params) {
    global $_CONFIG;
    $urlescapecodes = array(
        "\"" => "%22",
    );
    return $_CONFIG['directories']['baseURL'] . "?mode=service&page=$pageName&service=$serviceName&params=" . str_replace(array_keys($urlescapecodes), array_values($urlescapecodes), serialize($params));
}

function redirect($pageName, $subpageName, $params = array()) {
    global $_CONFIG;
    $urlescapecodes = array(
        "\"" => "%22",
    );
    header("Location: " . $_CONFIG['directories']['baseURL'] . "/index.php?choice=$pageName&subpage=$subpageName&params=" . str_replace(array_keys($urlescapecodes), array_values($urlescapecodes), serialize($params)));
}

function buildRedirectURL($pageName, $subpageName, $params) {
    global $_CONFIG;
    $urlescapecodes = array(
        "\"" => "%22",
    );
    return ($_CONFIG['directories']['baseURL'] . "/index.php?choice=$pageName&subpage=$subpageName&params=" . str_replace(array_keys($urlescapecodes), array_values($urlescapecodes), serialize($params)));
}

function loadJQueryPlugin($pluginName) {
    global $loadedPlugins;

    $file = "site/resources/js/jquery.$pluginName.js";
    if (file_exists($file)) {
        $loadedPlugins[] = $file;
    }
}

function loadPageJavascripts($pageName) {
    global $pagejs;
    $file = "site/pages/$pageName/resources/js/$pageName.js";
    if (file_exists($file)) {
        $pagejs[] = $file;
    }
}

?>
